using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MVCWeekOne.Models;
using System.Text.Json;

namespace MVCWeekOne.Controllers
{
    public class RouteController : Controller
    {
        private readonly HttpClient _httpClient;
        private readonly ApiSettings _apiSettings;
        private readonly ILogger<RouteController> _logger;

        public RouteController(HttpClient httpClient, IOptions<ApiSettings> apiSettings, ILogger<RouteController> logger)
        {
            _httpClient = httpClient;
            _apiSettings = apiSettings.Value;
            _logger = logger;
        }

        /// <summary>
        /// 工艺路线管理首页
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Index(int page = 1, int size = 20, string? routeCode = null, string? routeName = null)
        {
            try
            {
                var queryParams = new List<string>
                {
                    $"index={page}",
                    $"size={size}"
                };

                if (!string.IsNullOrEmpty(routeCode))
                    queryParams.Add($"routeCode={Uri.EscapeDataString(routeCode)}");
                
                if (!string.IsNullOrEmpty(routeName))
                    queryParams.Add($"routeName={Uri.EscapeDataString(routeName)}");

                var queryString = string.Join("&", queryParams);
                var url = $"{_apiSettings.ReadApiUrl}/Route/page?{queryString}";

                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                var jsonString = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<ApiPageing<RouteDto>>(jsonString, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                ViewBag.CurrentPage = page;
                ViewBag.ReadApiUrl = _apiSettings.ReadApiUrl;
                ViewBag.WriteApiUrl = _apiSettings.WriteApiUrl;
                ViewBag.PageSize = size;
                ViewBag.TotalCount = result?.TotaCount ?? 0;
                ViewBag.TotalPages = result?.TotaPage ?? 0;
                ViewBag.RouteCode = routeCode;
                ViewBag.RouteName = routeName;

                return View(result?.PageData ?? new List<RouteDto>());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工艺路线列表失败");
                ViewBag.ErrorMessage = "获取工艺路线列表失败，请稍后重试";
                return View(new List<RouteDto>());
            }
        }

        /// <summary>
        /// 获取工艺路线详情
        /// </summary>
        /// <param name="id">工艺路线ID</param>
        /// <returns></returns>
        public async Task<IActionResult> Detail(int id)
        {
            try
            {
                var url = $"{_apiSettings.ReadApiUrl}/Route/{id}";
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                var jsonString = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<ApiResult<RouteDetailDto>>(jsonString, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                if (result?.IsSuccess == true && result.Data != null)
                {
                    return View(result.Data);
                }
                else
                {
                    ViewBag.ErrorMessage = result?.Msg ?? "获取工艺路线详情失败";
                    return View(new RouteDetailDto());
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工艺路线详情失败，ID: {RouteId}", id);
                ViewBag.ErrorMessage = "获取工艺路线详情失败，请稍后重试";
                return View(new RouteDetailDto());
            }
        }

        /// <summary>
        /// AJAX获取工艺路线详情（用于弹窗显示）
        /// </summary>
        /// <param name="id">工艺路线ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetRouteDetail(int id)
        {
            try
            {
                var url = $"{_apiSettings.ReadApiUrl}/Route/{id}";
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                var jsonString = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<ApiResult<RouteDetailDto>>(jsonString, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                if (result?.IsSuccess == true && result.Data != null)
                {
                    return Json(new { code = 200, data = result.Data, message = "获取成功" });
                }
                else
                {
                    return Json(new { code = 500, message = result?.Msg ?? "获取工艺路线详情失败" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工艺路线详情失败，ID: {RouteId}", id);
                return Json(new { success = false, message = "获取工艺路线详情失败，请稍后重试" });
            }
        }

        /// <summary>
        /// API端点：获取工艺路线详情
        /// </summary>
        /// <param name="id">工艺路线ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Route/{id}")]
        public async Task<IActionResult> GetRouteDetailApi(int id)
        {
            try
            {
                var url = $"{_apiSettings.ReadApiUrl}/Route/{id}";
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                var jsonString = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<ApiResult<RouteDetailDto>>(jsonString, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                if (result?.IsSuccess == true && result.Data != null)
                {
                    return Json(new { code = 200, data = result.Data, message = "获取成功" });
                }
                else
                {
                    return Json(new { code = 500, message = result?.Msg ?? "获取工艺路线详情失败" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工艺路线详情失败，ID: {RouteId}", id);
                return Json(new { code = 500, message = "获取工艺路线详情失败，请稍后重试" });
            }
        }

        /// <summary>
        /// 新增工艺路线页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Add()
        {
            ViewBag.ReadApiUrl = _apiSettings.ReadApiUrl;
            ViewBag.WriteApiUrl = _apiSettings.WriteApiUrl;
            return View();
        }

        /// <summary>
        /// 编辑工艺路线页面
        /// </summary>
        /// <param name="id">工艺路线ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Edit(int id)
        {
            try
            {
                var url = $"{_apiSettings.ReadApiUrl}/Route/{id}";
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                var jsonString = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<ApiResult<RouteDetailDto>>(jsonString, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                ViewBag.ReadApiUrl = _apiSettings.ReadApiUrl;
                ViewBag.WriteApiUrl = _apiSettings.WriteApiUrl;

                if (result?.IsSuccess == true && result.Data != null)
                {
                    return View(result.Data);
                }
                else
                {
                    ViewBag.ErrorMessage = result?.Msg ?? "获取工艺路线详情失败";
                    return View(new RouteDetailDto());
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工艺路线详情失败，ID: {RouteId}", id);
                ViewBag.ErrorMessage = "获取工艺路线详情失败，请稍后重试";
                return View(new RouteDetailDto());
            }
        }

        /// <summary>
        /// 下载工艺路线导入模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Template()
        {
            try
            {
                // 创建简单的Excel模板
                var templateContent = new[]
                {
                    "工艺路线编号,工艺路线名称,开启审批,备注",
                    "GYLX001,示例工艺路线1,是,这是示例数据",
                    "GYLX002,示例工艺路线2,否,请按照此格式填写数据"
                };

                var csvContent = string.Join("\n", templateContent);
                var bytes = System.Text.Encoding.UTF8.GetBytes(csvContent);

                return File(bytes, "application/vnd.ms-excel", "工艺路线导入模板.csv");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "下载模板失败");
                return Json(new { code = 500, message = "下载模板失败，请稍后重试" });
            }
        }
    }
} 